import $ from '../jquery/jquery.min.js';
import ajax from '../utils/ajax'


const searchObj = {
    value: '',
    currentPage: 1,
    pageSize: 5,
    pages: 0,
    total: 0
}

let names;

showContracts();
showPageData();
//打开合同
$('#contractManagement').on('click', '.show-contract-modal', function () {
    $('#add-houseRent-contract-modalbox').show();
        //获取选择要修改用户的数据渲染到模态框
        const _id = $(this).data('id');
        $("#house-title-h4").attr('data-id',_id);
        getcontractDatasById(_id);
 
});



//关闭房屋租赁合同
$('#houseRent-cancel-btn,#contract-cancel-btn').click(function () {
    $('#add-houseRent-contract-modalbox').hide();
});


//查询所有的合同数据
function showContracts() {
    ajax({
        url: "/contracts",
        type: 'GET',
        data: {
            searchObj,
            currentPage: searchObj.currentPage,
            pageSize: searchObj.pageSize,
        },
        success(res) {
            if (res.code == 200) {
                searchObj.pages = res.pages;
                searchObj.total = res.total;
                rederContractsData(res.result);
            } 
        }
    })
}

function rederContractsData(data) {
    $('#contract-tb tbody').html(data.map(item => `<tr>
    <td>${item.contractNumber}</td>
    <td>${item.contractName}</td>
    <td>${item.numbers}</td>
    <td>${getType(item.start_date, getDate(), item.off_hire) ? '正在执行' : "已失效"}</td>
    <td>${item.tenant}</td>
    <td>${item.leaseeContacts}</td>
    <td>${item.leaseeTel}</td>
    <td>${item.signingDate}</td>
    <td>${item.start_date}</td>
    <td>${item.off_hire}</td>
    <td>${item.price}</td>
    <td><span data-id=${item._id} class='contract-detail-btn' >详情</span><span class='show-contract-modal' data-id=${item._id}>变更</span><span data-id=${item._id} class='del-contract-btn'>退租</span></td>
</tr>`).join(''));
}



//获取当前日期
function getDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = parseInt(date.getMonth()) + 1;
    const day = date.getDate();
    return `${year}-0${month}-${day}`;
}




//判断合同状态
function getType(data1, data2, data3) {
    const date1 = new Date(data1);
    const date2 = new Date(data2);
    const date3 = new Date(data3);
    if (date2 >= date1 && date2 <= date3) {
        return true;
    } else {
        return false;
    }
}



// 渲染页码相关div
function showPageData() {
    ajax({
        url: "/contracts",
        type: 'GET',
        data: {
            searchObj,
            currentPage: searchObj.currentPage,
            pageSize: searchObj.pageSize,
        },
        success(res) {
            if (res.code == 200) {
                renderPageData(Number(res.pages));
            } 
        }
    })
}

function renderPageData(pages) {
    let html = '';
    for (let i = 1; i <= pages; i++) {
        html += `<span>${i}</span>`;
    }
    $('#contract-bottom-choose-page-div .add-pages-span').html(html);
    $('#contract-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#contract-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
}



//点击切换页面
$('#contract-bottom-choose-page-div .add-pages-span').on('click', 'span', function () {
    $('#contract-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(this).addClass('active');
    const currentPage = $(this).text();
    searchObj.currentPage = Number(currentPage);
  showContracts();
});

//点击切换页面显示条数
$('#contract-pageSize-select').change(function () {
    const pageSize = $('#contract-pageSize-select').val();
    searchObj.pageSize = Number(pageSize);
    searchObj.currentPage = 1;
   showContracts();
    showPageData();
});


//跳至X页事件
$('#contract-go-page').keyup(function (e) {
    if (e.keyCode == 13) {
        const page = $('#contract-go-page').val();
        if (page != '' && typeof Number(page) == 'number' && !isNaN(Number(page))) {
            if (Number(page) < 1) {
                searchObj.currentPage = 1;
              showContracts();
                $('#contract-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#contract-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            } else if (Number(page) > searchObj.pages) {
                searchObj.currentPage = searchObj.pages;
              showContracts();
                $('#contract-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#contract-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            } else {
                searchObj.currentPage = Number(page);
              showContracts();
                $('#contract-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#contract-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            }
        }
    }
});


//上一页，下一页事件
$('#contract-prev-span').click(function () {
    if (searchObj.currentPage <= 1) {
        searchObj.currentPage = 1;
    } else {
        searchObj.currentPage--;
    }
   showContracts();
    $('#contract-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#contract-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
});


$('#contract-next-span').click(function () {
    if (searchObj.currentPage == searchObj.pages) {
        searchObj.currentPage = searchObj.pages;
    } else {
        searchObj.currentPage++;
    }
   showContracts();
    $('#contract-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#contract-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
});


//点击搜索按钮查询
$('#search-contract-btn').click(function () {
    const value = $('#search-contract').val();
    searchObj.value = value;
    searchObj.currentPage = 1;
   showContracts();
    showPageData();
});





//点击删除按钮，删除对应客户数据
$('#contract-tb tbody').on('click', '.del-contract-btn', function () {
    const _id = $(this).data('id');
    const isDel=confirm('确认退租?');
    if(isDel){
        delContractData(_id);
    }
});


//删除客户数据
function delContractData(_id) {
    ajax({
        url: '/contracts',
        data: { _id },
        type: "DELETE",
        success(res) {
            if (res.code == 200) {
                // 删除成功
                if ((searchObj.total) % (searchObj.pageSize) == 1) {
                    $('#contract-tb tbody tr').length == 1 ? searchObj.currentPage-- : searchObj.currentPage;
                    showPageData();
                }
                showContracts();
            } else {
                alert('抱歉,删除失败');
            }
        }
    })
}



//通过id查询对应的房屋详细合同资料
function  getcontractDatasById(_id) {
    ajax({
        url: '/contracts/' + _id,
        type: "GET",
        success(res) {
            if (res.code == 200) {
                $('#contract-contractNumber').val(res.result.contractNumber);
                $('#contract-tenant').val(res.result.tenant);
                $('#contract-signingDate').val(res.result.signingDate);
                $('#contract-representative').val(res.result.representative);
                $('#contract-tenantContacts').val(res.result.tenantContacts);
                $('#contract-contractType').val(res.result.contractType);
                $('#contract-term').val(res.result.term);
                $('#contract-off_hire').val(res.result.off_hire);
                $('#contract-start_date').val(res.result.start_date);
                $('#contract-area').val(res.result.area);
                $('#contract-earnestMoney').val(res.result.earnestMoney);
                $('#contract-agencyfee').val(res.result.agencyfee);
                $('#contract-isRentMoney').prop('checked',res.result.isRentMoney);
                $('#contract-totalMoney').val(res.result.totalMoney);
                $('#contract-increase').val(res.result.increase);
                $('#contract-earnestExplain').val(res.result.earnestExplain);
                $('#contract-remark').val(res.result.remark);
                $('#houseRent-accessory-btn').attr('src',res.result.accessory);
                names=res.result.contractName;
            } 
        }
    })
}




//修改合同
$('#houseRent-ok-btn').click(function () {
    //获取当前输入框的值
    const contractNumber = $('#contract-contractNumber').val();
    const tenant = $('#contract-tenant').val();
    const signingDate = $('#contract-signingDate').val();
    const representative = $('#contract-representative').val();
    const tenantContacts = $('#contract-tenantContacts').val();
    const contractType = $('#contract-contractType').val();
    const term = $('#contract-term').val();
    const off_hire = $('#contract-off_hire').val();
    const start_date = $('#contract-start_date').val();
    const area = $('#contract-area').val();
    const earnestMoney = $('#contract-earnestMoney').val();
    const agencyfee = $('#contract-agencyfee').val();
    const isRentMoney = $('#contract-isRentMoney').prop('checked');
    const totalMoney = $('#contract-isRentMoney').prop('checked') ? $('#contract-totalMoney').val() : 0;
    const increase = $('#contract-increase').val();
    const earnestExplain = $('#contract-earnestExplain').val();
    const remark = $('#contract-remark').val();
    const accessory = $('#houseRent-accessory-btn').attr('src');
    const contractName=names;
    if(contractNumber!=''&&tenant
    !=''&&signingDate!=''&&representative!=''&&tenantContacts!=''&&contractType!=''&&term!=''&&off_hire!=''&&start_date!=''&&area
    !=''&&earnestMoney!=''&&agencyfee!=''&&isRentMoney!=''&&totalMoney!=''&&increase!=''&&earnestExplain!=''&&remark!=''&&accessory!=''){
            //编辑
    const _id = $('#house-title-h4').data('id');
            ajax({
                url: '/contracts',
                type: "PUT",
                data: {
                    _id,
                    contractNumber,
                    tenant,
                    signingDate,
                    representative,
                    tenantContacts,
                    contractType,
                    term,
                    off_hire,
                    start_date,
                    area,
                    earnestMoney,
                    agencyfee,
                    isRentMoney,
                    totalMoney,
                    increase,
                    earnestExplain,
                    remark,
                    accessory,
                    contractName
                },
                success(res) {
                    if (res.code == 200) {
                        alert("修改合同成功");
                        $('#add-houseRent-contract-modalbox').hide();
                        showContracts();
                        clearData();
                    } else {
                        alert("修改合同失败");
                        $('#add-houseRent-contract-modalbox').hide();
                        clearData();
                    }
                }
            });
    }else{
        alert('输入框都不能为空!')
    }
});



//清除模态框数据
function clearData(){
    $('#contract-contractNumber').val('');
    $('#contract-tenant').val('');
    $('#contract-signingDate').val('');
    $('#contract-representative').val('');
    $('#contract-tenantContacts').val('');
    $('#contract-contractType').val('');
    $('#contract-term').val('');
    $('#contract-off_hire').val('');
    $('#contract-start_date').val('');
    $('#contract-area').val('');
    $('#contract-earnestMoney').val('');
    $('#contract-agencyfee').val('');
    $('#contract-isRentMoney').prop('checked',false);
    $('#contract-totalMoney').val('');
    $('#contract-increase').val('');
    $('#contract-earnestExplain').val('');
    $('#contract-remark').val('');
}





//上传图片
$('#file-input-contract').change(function (e) {
    const files = e.target.files;
    const fd = new FormData();
    fd.append('file', files[0]);
    $.ajax({
        url: 'http://localhost:3100/contracts/uploadImages',
        type: "POST",
        data: fd,
        contentType: false,
        processData: false,
        cache: false,
        success(res) {
            if (res.code == 200) {
                $('#houseRent-accessory-btn').attr('src', 'http://localhost:3100/' + res.data);
            }
        }
    });
});




//点击详情查询合同图片
$('#contract-tb tbody').on('click', '.contract-detail-btn', function () {
    const _id = $(this).data('id');
    getContractImgByid(_id);
});



//通过id查询对应的房屋租赁合同图片数据
function getContractImgByid(_id) {
    ajax({
        url: '/contracts/' + _id,
        type: "GET",
        success(res) {
            if (res.code == 200) {
                $('#show-img-div').show();
                $('#cancle-img').attr('src', res.result.accessory);
            } 
        }
    })
}
